package respository

import (
	"gitee.com/song-yao-shun/MQH/common"
	"gitee.com/song-yao-shun/MQH/model"
	"gitee.com/song-yao-shun/MQH/vo"
	"gorm.io/gorm"
	"log"
)

//定义接口和定义增删改查的方法
type IApplicationRepository interface {
	Create(app model.Application)
	Update(app model.Application)
	SelectById(Id int)
	DeleteById(Id int)
	List(appList vo.ApplicationList)
}

type ApplicationRepository struct {
	DB *gorm.DB
}

func (a ApplicationRepository) Create(app model.Application) (int, error){

	if err := a.DB.Create(&app).Error; err != nil {
		log.Printf("新增失败，错误信息为：%v",err)
		return 0, err
	}

	return app.ID, nil
}

func (a ApplicationRepository) Update(app model.Application) (*model.Application, error){

	if err := a.DB.Updates(&app).Error;err != nil {
		return nil, err
	}

	return &app,nil
}

func (a ApplicationRepository) SelectById(Id int) (app *model.Application,err error) {

	if err := a.DB.First(&app, Id).Error; err != nil {
		return nil, err
	}

	return
}

func (a ApplicationRepository) DeleteById(Id int) (rowsAffected int64) {

	rowsAffected = a.DB.Delete(model.Application{}, Id).RowsAffected
	if rowsAffected != 1 {
		log.Printf("数据删除失败，删除操作影响行数为：%v，删除的id为：%v",rowsAffected,Id)
	}

	return
}

func (a ApplicationRepository) List(appList vo.ApplicationList) (applications []model.Application, total int64){
	// 条件查询
	//if  appList.SelectField != ""{
	//	a.DB = a.DB.Select(appList.SelectField)
	//}
	if appList.Name != ""  {
		a.DB = a.DB.Where("name like ?", "%" + appList.Name + "%")
	}
	if appList.PageNum == 0  {
		appList.PageNum = 1
	}
	if appList.PageSize == 0  {
		appList.PageSize = 10
	}

	//总记录数
	a.DB.Model(model.Application{}).Count(&total)
	if total == 0 {
		return
	}

	a.DB.Order("created_at desc").Offset((appList.PageNum -1) * appList.PageSize).Limit(appList.PageSize).Find(&applications)

	return
}

func NewApplicationRepository() ApplicationRepository{
	db := common.GetDB()
	//db.AutoMigrate(model.Application{})

	return ApplicationRepository{DB: db}
}